package com.fzx.fzwsupplysystem.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.fzx.fzwsupplysystem.MyApplication;
import com.fzx.fzwsupplysystem.R;
import com.fzx.fzwsupplysystem.bean.CardInfo;
import com.fzx.fzwsupplysystem.bean.PersonBean;
import com.fzx.fzwsupplysystem.util.AppConstant;
import com.fzx.fzwsupplysystem.util.CountTimes;
import com.fzx.fzwsupplysystem.util.JsonCallback;
import com.fzx.fzwsupplysystem.view.CountTimeTextView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.zkteco.android.IDReader.IDCardRead;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;
import com.zkteco.android.biometric.module.idcard.meta.IDPRPCardInfo;

import java.io.Serializable;
import java.lang.ref.WeakReference;

/**
 * 类名：MainActivity.java
 * 创建人：FangZhiXin
 * 时间：2019/11/12 10:07
 * 描述：身份证读取页面，读取身份证，然后查询后台信息
 */
public class MainActivity extends BaseActivity {

    private static final String TAG = "MainActivity";
    private IDCardRead mIDCardRead;
    private String idInfo = "";
    private Bitmap photoBitmap;

    private Button btn_other;
    private CountTimeTextView tv_count;

    private MyHandler myHandler;
    private static final int H_READ_CARD = 101;
    private static final int H_CLOSE_CARD = 102;
    private static final int H_OPEN_ERROR = 103;
    private boolean isGotoFace = false;

    public void OnBack(View view) {
        finishAc();
    }

    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> mActivity;

        private MyHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case H_OPEN_ERROR:
                        //这里弹框提示设备打开失败，选择退出或者重新读取
                        Toast.makeText(activity, "设备打开失败", Toast.LENGTH_SHORT).show();
                        activity.showMessageDialog("提示", "设备打开失败，请联系管理人员！", false, true);
                        break;
                    case H_READ_CARD:
                        boolean b = activity.onStartReadIDCard();
                        if (b) {
                            //启动读身份证线程成功，等待回调结果
                            Toast.makeText(activity, "开始读取身份证", Toast.LENGTH_SHORT).show();
                        } else {
                            activity.onStopReadIDCard();
                            //启动读身份证线程失败，这里弹框提示读身份证失败或者重新读取
                        }
                        break;

                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myHandler = new MyHandler(this);
        initView();
        initIDCard();

    }

    private void initView() {
        btn_other = findViewById(R.id.btn_other);
        btn_other.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //这里进入下一个页面，输入其他证件信息
                if (isGotoFace) {
                    return;
                }
                gotoAc(OtherCardActivity.class);
                onStopReadIDCard();
                boolean close = close();
            }
        });
        tv_count = findViewById(R.id.tv_count);


    }

    private void initIDCard() {
        mIDCardRead = new IDCardRead(this);
        mIDCardRead.setIDCardLister(mIDCardListen);
    }

    private IDCardRead.getIDCardInfoListen mIDCardListen = new IDCardRead.getIDCardInfoListen() {
        @Override
        public void getIDCardInfo(final int type,//证件类型
                                  final IDCardInfo idcardinfo,//中国大陆居民身份证
                                  final IDPRPCardInfo idprpCardInfo, //外国人永居证
                                  final IDCardInfo GATIdcardinfo,//港澳台居住证
                                  final Bitmap idcardBitmap)//身份证头像
        {
            if (isFinishing()) {
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (type == 1) {//中国大陆居民身份证
                        CardInfo.name = idcardinfo.getName();
                        CardInfo.sex = idcardinfo.getSex();
                        CardInfo.nation = idcardinfo.getNation();
                        CardInfo.birthday = idcardinfo.getBirth();
                        CardInfo.address = idcardinfo.getAddress();
                        CardInfo.idNumber = idcardinfo.getId();
                        CardInfo.office = idcardinfo.getDepart();
                        CardInfo.validityTime = idcardinfo.getValidityTime();
                        CardInfo.photoBmp = idcardBitmap;
                        AppConstant.cardId = idcardinfo.getId();
                        if (MyApplication.isDebug) {
                            AppConstant.cardId = AppConstant.DEFAULT_ID;
                        }
                        idInfo = "姓名：" + idcardinfo.getName() + "\n" +
                                "性别：" + idcardinfo.getSex() + "\n" +
                                "民族：" + idcardinfo.getNation() + "\n" +
                                "出生日期：" + idcardinfo.getBirth() + "\n" +
                                "住址：" + idcardinfo.getAddress() + "\n" +
                                "身份证号：" + idcardinfo.getId() + "\n" +
                                "签发机关：" + idcardinfo.getDepart() + "\n" +
                                "有效期限：" + idcardinfo.getValidityTime();
                        photoBitmap = idcardBitmap;
                        Log.i(TAG, "IDCardRead: " + idInfo);
                        isGotoFace = true;
                        //这里请求人员信息
                        requestPersonStatus();

                    } else if (type == 2) {//外国人永居证

                    } else if (type == 3) {//港澳台居住证

                    }
                }
            });
            Log.d(TAG, "更换了身份证....");
        }
    };

    /**
     * 读取身份证后，请求个人信息
     */
    private void requestPersonStatus() {
        if (isFinishing()) {
            return;
        }
        OkGo.<PersonBean>get(AppConstant.URL_PERSON_INFO).tag(this)
                .params("idCard", AppConstant.cardId)//身份证号
                .params("matchId", AppConstant.matchId)//赛事id
                .execute(new JsonCallback<PersonBean>(PersonBean.class) {
                    @Override
                    public void onSuccess(Response<PersonBean> response) {
                        Log.i(TAG, "onSuccess: ");
                        if (isFinishing()) {
                            return;
                        }
                        if (response == null) {
                            showMessageDialog("提示", "数据异常，请联系管理人员！", false, true);
                            return;
                        }
                        PersonBean personBean = response.body();
                        if (personBean == null) {
                            showMessageDialog("提示", "数据异常，请联系管理人员！", false, true);
                            return;
                        }
                        String code = personBean.getCode();
                        if ("000000".equals(code)) {
                            //正常有数据
                            String status = personBean.getStatus();
                            if ("0".equals(status)) {
                                //未领取,进入人脸识别
                                Intent intent = new Intent(MainActivity.this, FaceCompareActivity.class);
                                intent.putExtra("PersonBean", (Serializable) personBean);
                                startActivity(intent);
                            } else if ("1".equals(status)) {
                                showMessageDialog("温馨提示", "您已打印过领物单，请勿重复打印，谢谢！", false, true);
                            }
                        } else {
                            showMessageDialog("温馨提示", "抱歉，没有您的参赛信息，如有疑问，请联系现场工作人员！", false, true);
                        }
                    }

                    @Override
                    public void onError(Response<PersonBean> response) {
                        if (response == null) {
                            showMessageDialog("提示", "请求异常，请联系管理人员！", false, true);
                            return;
                        }
                        Log.i(TAG, "onError: " + response.getException());
                        showMessageDialog("提示", "请求异常，" + response.message(), false, true);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        isGotoFace = false;
                    }
                });
    }


    @Override
    protected void onResume() {
        super.onResume();
        startTimeDown();
        boolean open = open();
        if (open) {
            myHandler.sendEmptyMessageDelayed(H_READ_CARD, 200);
        } else {
            myHandler.sendEmptyMessageDelayed(H_OPEN_ERROR, 200);
        }
    }

    /**
     * 启动倒计时，在页面获取到焦点后执行
     */
    private void startTimeDown() {
        tv_count.startTimeDown(AppConstant.CountTime, 1, new CountTimes.OnCountTimeListener() {
            @Override
            public void onStart(int time) {
                tv_count.setText("" + time);
            }

            @Override
            public void onTick(int time) {
                tv_count.setText("" + time);
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFinish(int time) {
                gotoHome();
            }
        });
    }

    /**
     * 停止倒计时，释放
     */
    private void releaseTimeDown() {
        tv_count.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        myHandler.removeMessages(H_READ_CARD);
    }

    @Override
    protected void onStop() {
        super.onStop();
        releaseTimeDown();
        onStopReadIDCard();
        boolean close = close();
        OkGo.getInstance().cancelAll();
    }

    private boolean open() {
        return mIDCardRead.openDevice();
    }

    private boolean close() {
        return mIDCardRead.closeDevice();
    }

    private boolean onStartReadIDCard() {
        return mIDCardRead.startIDThread();
    }

    public void onStopReadIDCard() {
        mIDCardRead.stopIDThread();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
